﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Wpf.Netdisk.Extensions
{
    public class NetworkSpeed
    {
        private long _bytesSent;
        private long _bytesReceived;
        private DateTime _lastChecked;

        public NetworkSpeed()
        {
            _lastChecked = DateTime.Now;
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface ni in interfaces)
            {
                if (ni.OperationalStatus == OperationalStatus.Up)
                {
                    _bytesSent += ni.GetIPv4Statistics().BytesSent;
                    _bytesReceived += ni.GetIPv4Statistics().BytesReceived;
                }
            }
        }

        public double UploadSpeed
        {
            get
            {
                TimeSpan timePassed = DateTime.Now - _lastChecked;
                long bytesSentNow = 0;
                NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

                foreach (NetworkInterface ni in interfaces)
                {
                    if (ni.OperationalStatus == OperationalStatus.Up)
                    {
                        bytesSentNow += ni.GetIPv4Statistics().BytesSent;
                    }
                }

                double speed = (bytesSentNow - _bytesSent) / timePassed.TotalSeconds / 1024;
                _bytesSent = bytesSentNow;
                _lastChecked = DateTime.Now;
                return speed;
            }
        }

        public double DownloadSpeed
        {
            get
            {
                TimeSpan timePassed = DateTime.Now - _lastChecked;
                long bytesReceivedNow = 0;
                NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

                foreach (NetworkInterface ni in interfaces)
                {
                    if (ni.OperationalStatus == OperationalStatus.Up)
                    {
                        bytesReceivedNow += ni.GetIPv4Statistics().BytesReceived;
                    }
                }

                double speed = (bytesReceivedNow - _bytesReceived) / timePassed.TotalSeconds ;
                _bytesReceived = bytesReceivedNow;
                _lastChecked = DateTime.Now;
                return speed;
            }
        }
    }
}
